﻿using GedeaProject.Entities;
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Shapes;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.Rendering;
using PdfSharp.Pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GedeaProject.Business.PdfWriter
{
    public class PdfClass2
    {
        public void CreatePdf(DebitOrder debitOrder)
        {
            // Create a MigraDoc document
            Document document = CreateDocument(debitOrder);
            document.UseCmykColor = true;

            // A flag indicating whether to create a Unicode PDF or a WinAnsi PDF file.
            // This setting applies to all fonts used in the PDF document.
            // This setting has no effect on the RTF renderer.
            const bool unicode = false;

            // An enum indicating whether to embed fonts or not.
            // This setting applies to all font programs used in the document.
            // This setting has no effect on the RTF renderer.
            // (The term 'font program' is used by Adobe for a file containing a font. Technically a 'font file'
            // is a collection of small programs and each program renders the glyph of a character when executed.
            // Using a font in PDFsharp may lead to the embedding of one or more font programms, because each outline
            // (regular, bold, italic, bold+italic, ...) has its own fontprogram)
            const PdfFontEmbedding embedding = PdfFontEmbedding.Always;

            // ========================================================================================

            // Create a renderer for the MigraDoc document.
            PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(unicode, embedding);

            // Associate the MigraDoc document with a renderer
            pdfRenderer.Document = document;

            // Layout and render document to PDF
            pdfRenderer.RenderDocument();

            // Save the document...
            string filename = "C:\\Users\\Ignacio\\Desktop\\Test.pdf";
            int nameTries = 1;

            while(File.Exists(filename))
            {
                filename = "C:\\Users\\Ignacio\\Desktop\\Test(" + nameTries +").pdf";
                nameTries++;
            }

            pdfRenderer.PdfDocument.Save(filename);
        }
        public Document CreateDocument(DebitOrder debitOrder)
        {
            // Create a new MigraDoc document
            var document = new Document(); 
            CreateDocumentInfo(document);
            DefineStyles(document);
            CreatePage(document, debitOrder);
            return document;
        }

        private static void CreateDocumentInfo(Document document)
        {

            document.Info.Title = "Debit Order";
            document.Info.Subject = "Related information";
            document.Info.Author = "Gedea Proyect";
        }

        void DefineStyles(Document document)
        {
            // Get the predefined style Normal.
            Style style = document.Styles["Normal"];
            // Because all styles are derived from Normal, the next line changes the 
            // font of the whole document. Or, more exactly, it changes the font of
            // all styles and paragraphs that do not redefine the font.
            style.Font.Name = "Verdana";
            
            style = document.Styles[StyleNames.Header];
            style.ParagraphFormat.AddTabStop("16cm", TabAlignment.Right);
            
            style = document.Styles[StyleNames.Footer];
            style.ParagraphFormat.AddTabStop("8cm", TabAlignment.Center);
            
            // Create a new style called Table based on style Normal
            style = document.Styles.AddStyle("Table", "Normal");
            style.Font.Name = "Verdana";
            style.Font.Name = "Times New Roman";
            style.Font.Size = 9;
            
            // Create a new style called Reference based on style Normal
            style = document.Styles.AddStyle("Reference", "Normal");
            style.ParagraphFormat.SpaceBefore = "5mm";
            style.ParagraphFormat.SpaceAfter = "5mm";
            style.ParagraphFormat.TabStops.AddTabStop("16cm", TabAlignment.Right);
        }

        void CreatePage(Document document, DebitOrder debitOrder)
        {
            // Each MigraDoc document needs at least one section.
            Section section = document.AddSection();
            
            CreateHeader(section);
            CreateFooter(section);
            CreateTitle(section);

            Paragraph paragraph = section.AddParagraph("En el presente documento constan los datos concernientes a su homónimo en formato txt.");
            paragraph.Format.SpaceBefore = "1cm";

            CreateOriginant(section, debitOrder.Company);
            

            // Add the print date field
            Paragraph paragraph2 = section.AddParagraph();
            paragraph2.Format.SpaceBefore = "1cm";
            paragraph2.Style = "Reference";
            paragraph2.AddFormattedText("INVOICE", TextFormat.Bold);
            paragraph2.AddTab();
            paragraph2.AddText("Cologne, ");
            paragraph2.AddDateField("dd.MM.yyyy");
            
            // Create the item table
            Table table = section.AddTable();
            table.Style = "Table";
            table.Borders.Color = new Color(1, 0, 0); // TableBorder;
            table.Borders.Width = 0.25;
            table.Borders.Left.Width = 0.5;
            table.Borders.Right.Width = 0.5;
            table.Rows.LeftIndent = 0;

            // Before you can add a row, you must define the columns
            Column column = table.AddColumn("1cm");
            column.Format.Alignment = ParagraphAlignment.Center;
            
            column = table.AddColumn("2.5cm");
            column.Format.Alignment = ParagraphAlignment.Right;
            
            column = table.AddColumn("3cm");
            column.Format.Alignment = ParagraphAlignment.Right;
            
            column = table.AddColumn("3.5cm");
            column.Format.Alignment = ParagraphAlignment.Right;
            
            column = table.AddColumn("2cm");
            column.Format.Alignment = ParagraphAlignment.Center;
            
            column = table.AddColumn("4cm");
            column.Format.Alignment = ParagraphAlignment.Right;

            
            // Create the header of the table
            Row row = table.AddRow();
            row.HeadingFormat = true;
            row.Format.Alignment = ParagraphAlignment.Center;
            row.Format.Font.Bold = true;
            row.Shading.Color = new Color(0, 1, 0); // TableBlue;
            row.Cells[0].AddParagraph("Item");
            row.Cells[0].Format.Font.Bold = false;
            row.Cells[0].Format.Alignment = ParagraphAlignment.Left;
            row.Cells[0].VerticalAlignment = VerticalAlignment.Bottom;
            row.Cells[0].MergeDown = 1;
            row.Cells[1].AddParagraph("Title and Author");
            row.Cells[1].Format.Alignment = ParagraphAlignment.Left;
            row.Cells[1].MergeRight = 3;
            row.Cells[5].AddParagraph("Extended Price");
            row.Cells[5].Format.Alignment = ParagraphAlignment.Left;
            row.Cells[5].VerticalAlignment = VerticalAlignment.Bottom;
            row.Cells[5].MergeDown = 1;
            
            row = table.AddRow();
            row.HeadingFormat = true;
            row.Format.Alignment = ParagraphAlignment.Center;
            row.Format.Font.Bold = true;
            row.Shading.Color = new Color(0, 0, 1); // TableBlue;
            row.Cells[1].AddParagraph("Quantity");
            row.Cells[1].Format.Alignment = ParagraphAlignment.Left;
            row.Cells[2].AddParagraph("Unit Price");
            row.Cells[2].Format.Alignment = ParagraphAlignment.Left;
            row.Cells[3].AddParagraph("Discount (%)");
            row.Cells[3].Format.Alignment = ParagraphAlignment.Left;
            row.Cells[4].AddParagraph("Taxable");
            row.Cells[4].Format.Alignment = ParagraphAlignment.Left;
            
            table.SetEdge(0, 0, 6, 2, Edge.Box, BorderStyle.Single, 0.75, Color.Empty);

            FillContent(document, table);
        }

        private static void CreateOriginant(Section section, Company company)
        {
            Paragraph paragraph2 = section.AddParagraph();
            paragraph2.Format.SpaceBefore = "1cm";
            paragraph2.Style = "Reference";
            paragraph2.AddFormattedText("Ente originante", TextFormat.Bold);
            paragraph2.AddTab();
            paragraph2.AddText("Buenos Aires, ");
            paragraph2.AddDateField("dd.MM.yyyy");

            Table table = section.AddTable();
            table.Style = "Table";
            table.Borders.Color = new Color(1, 0, 0); // TableBorder;
            table.Borders.Width = 0.25;
            table.Borders.Left.Width = 0.5;
            table.Borders.Right.Width = 0.5;
            table.Rows.LeftIndent = 0;

            Column column = table.AddColumn("4cm");
            column.Format.Alignment = ParagraphAlignment.Right;

            column = table.AddColumn("12cm");
            column.Format.Alignment = ParagraphAlignment.Left;


            Row row = table.AddRow();
            row.Cells[0].AddParagraph("Empresa");
            row.Cells[0].Borders.Visible = false;
            row.Cells[0].Format.Font.Bold = true;
            row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
            row.Cells[1].AddParagraph(company.NameForBank);
            row.Cells[1].Format.Alignment = ParagraphAlignment.Left;

            row = table.AddRow();
            row.Cells[0].AddParagraph("Cuit");
            row.Cells[0].Borders.Visible = false;
            row.Cells[0].Format.Font.Bold = true;
            row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
            row.Cells[1].AddParagraph(company.Cuit);
            row.Cells[1].Format.Alignment = ParagraphAlignment.Left;

            row = table.AddRow();
            row.Cells[0].AddParagraph("Concepto/Beneficio");
            row.Cells[0].Borders.Visible = false;
            row.Cells[0].Format.Font.Bold = true;
            row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
            row.Cells[1].AddParagraph(company.Benefit);
            row.Cells[1].Format.Alignment = ParagraphAlignment.Left;
        }

        private static void CreateTitle(Section section)
        {
            //TextFrame titleFrame = section.AddTextFrame();
            //titleFrame.Height = "3.0cm";
            //titleFrame.Width = "7.0cm";
            //titleFrame.Left = ShapePosition.Center;
            //titleFrame.RelativeHorizontal = RelativeHorizontal.Margin;
            //titleFrame.Top = "3.5cm";
            //titleFrame.RelativeVertical = RelativeVertical.Page;

            Paragraph titleParagraph = section.AddParagraph();
            titleParagraph.Format.Font.Color = new Color(63, 67, 1, 19);
            titleParagraph.Format.Font.Size = 14;
            titleParagraph.Format.SpaceBefore = "1cm";
            titleParagraph.AddText("Informe de solicitud de débito");
        }

        private static void CreateHeader(Section section)
        {
            Image image = section.Headers.Primary.AddImage(@"C:\Users\Ignacio\Pictures\Gedea\promote-your-website-with-a-bit-of-money.jpg");
            image.Height = "3cm";
            image.LockAspectRatio = true;
            image.RelativeVertical = RelativeVertical.Line;
            image.RelativeHorizontal = RelativeHorizontal.Margin;
            image.Top = ShapePosition.Top;
            image.Left = ShapePosition.Right;
            image.WrapFormat.Style = WrapStyle.Through;

            Paragraph paragraph = section.Headers.Primary.AddParagraph("- ORDEN DE DEBITO -");
            paragraph.Format.Font.Bold = true;
            paragraph.Format.Font.Size = 16;
            paragraph.Format.Alignment = ParagraphAlignment.Center;
        }

        private void CreateFooter(Section section)
        {
            Paragraph paragraph = section.Footers.Primary.AddParagraph();
            paragraph.AddText("PowerBooks Inc · Sample Street 42 · 56789 Cologne · Germany");
            paragraph.Format.Font.Size = 9;
            paragraph.Format.Alignment = ParagraphAlignment.Center;
        }


        void FillContent(Document document, Table table)
        {
            // Iterate the invoice items
            double totalExtendedPrice = 0;
            for (int i = 5; i > 0; i--)
            {
                double quantity = 5;
                double price = 20;
                double discount = 10;
                
                // Each item fills two rows
                Row row1 = table.AddRow();
                Row row2 = table.AddRow();
                row1.TopPadding = 1.5;
                row1.Cells[0].Shading.Color = new Color(1, 0, 0); // TableGray;
                row1.Cells[0].VerticalAlignment = VerticalAlignment.Center;
                row1.Cells[0].MergeDown = 1;
                row1.Cells[1].Format.Alignment = ParagraphAlignment.Left;
                row1.Cells[1].MergeRight = 3;
                row1.Cells[5].Shading.Color = new Color(0, 1, 0); // TableGray;
                row1.Cells[5].MergeDown = 1;

                row1.Cells[0].AddParagraph(i.ToString());
                Paragraph paragraph = row1.Cells[1].AddParagraph();
                paragraph.AddFormattedText("[title]", TextFormat.Bold);
                paragraph.AddFormattedText("[ by ]", TextFormat.Italic);
                paragraph.AddText("[author]");
                row2.Cells[1].AddParagraph(23.ToString());
                row2.Cells[2].AddParagraph(price.ToString("0.00") + " €");
                row2.Cells[3].AddParagraph(discount.ToString("0.0"));
                row2.Cells[4].AddParagraph();
                row2.Cells[5].AddParagraph(price.ToString("0.00"));
                double extendedPrice = quantity * price;
                extendedPrice = extendedPrice * (100 - discount) / 100;
                row1.Cells[5].AddParagraph(extendedPrice.ToString("0.00") + " €");
                row1.Cells[5].VerticalAlignment = VerticalAlignment.Bottom;
                totalExtendedPrice += extendedPrice;

                table.SetEdge(0, table.Rows.Count - 2, 6, 2, Edge.Box, BorderStyle.Single, 0.75);
            }
            
            // Add an invisible row as a space line to the table
            Row row = table.AddRow();
            row.Borders.Visible = false;
            
            // Add the total price row
            row = table.AddRow();
            row.Cells[0].Borders.Visible = false;
            row.Cells[0].AddParagraph("Total Price");
            row.Cells[0].Format.Font.Bold = true;
            row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
            row.Cells[0].MergeRight = 4;
            row.Cells[5].AddParagraph(totalExtendedPrice.ToString("0.00") + " €");

            // Add the VAT row
            row = table.AddRow();
            row.Cells[0].Borders.Visible = false;
            row.Cells[0].AddParagraph("VAT (19%)");
            row.Cells[0].Format.Font.Bold = true;
            row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
            row.Cells[0].MergeRight = 4;
            row.Cells[5].AddParagraph((0.19 * totalExtendedPrice).ToString("0.00") + " €");

            // Add the additional fee row
            row = table.AddRow();
            row.Cells[0].Borders.Visible = false;
            row.Cells[0].AddParagraph("Shipping and Handling");
            row.Cells[5].AddParagraph(0.ToString("0.00") + " €");
            row.Cells[0].Format.Font.Bold = true;
            row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
            row.Cells[0].MergeRight = 4;
            
            // Add the total due row
            row = table.AddRow();
            row.Cells[0].AddParagraph("Total Due");
            row.Cells[0].Borders.Visible = false;
            row.Cells[0].Format.Font.Bold = true;
            row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
            row.Cells[0].MergeRight = 4;
            totalExtendedPrice += 0.19 * totalExtendedPrice;
            row.Cells[5].AddParagraph(totalExtendedPrice.ToString("0.00") + " €");
            
            // Set the borders of the specified cell range
            table.SetEdge(5, table.Rows.Count - 4, 1, 4, Edge.Box, BorderStyle.Single, 0.75);
            
            // Add the notes paragraph
            Paragraph paragraph2 = document.LastSection.AddParagraph();
            paragraph2.Format.SpaceBefore = "1cm";
            paragraph2.Format.Borders.Width = 0.75;
            paragraph2.Format.Borders.Distance = 3;
            paragraph2.Format.Borders.Color = new Color(0, 1, 0); // TableBorder;
            paragraph2.Format.Shading.Color = new Color(1, 0, 0); // TableGray;

            paragraph2.AddText("[notes]");
        }
    }
}
